package com.example.shardingjdbcdemo.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.sharding.api.sharding.standard.PreciseShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.RangeShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.StandardShardingAlgorithm;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Properties;

@Component
@Slf4j
public class TableAlgorithm implements StandardShardingAlgorithm<String> {
    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<String> preciseShardingValue) {
        String suffix = String.valueOf(this.hashShardingValue(preciseShardingValue.getValue()) % 256);
        String s = this.findMatchedTargetName(collection, suffix, preciseShardingValue.getDataNodeInfo()).orElse((null));
        return s;
    }

    @Override
    public Collection<String> doSharding(Collection<String> collection, RangeShardingValue<String> rangeShardingValue) {
        return null;
    }

    @Override
    public Properties getProps() {
        return null;
    }

    @Override
    public void init(Properties properties) {
        log.info("TableAlgorithm-init..:{}",properties);
    }

    private long hashShardingValue(Comparable<?> shardingValue) {
        return Math.abs((long)shardingValue.hashCode());
    }
}